# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1536643613': {  # witch 支付宝2.5%（1---5000）D0结算
        'API_KEY': '0a622a7080d809c4589f87c70cb22987',
        'gateway': 'https://api.tonghejinxian.com/pay/unifiedorder',
        'query_gateway': 'https://api.tonghejinxian.com/pay/query',
    },
    '1543821178': {  # witch 支付宝2.5%（1---5000）D0结算
        'API_KEY': '5426458cefbc6f6f4186077833106ebc',
        'gateway': 'https://pay.gs35g.cn/pay/unifiedorder',
        'query_gateway': 'https://pay.gs35g.cn/pay/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] is not None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    _LOGGER.info('xinfutongpay sign str : %s', s[:-1])
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("xinfutongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    return 'ALIH5'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('trade_type', _get_pay_type(service)),
        ('nonce', str(int(time.time()))),
        ('user_id', str(pay.user_id)),
        ('timestamp', str(int(time.time()))),
        ('subject', 'charge'),
        ('detail', 'charge'),
        ('out_trade_no', str(pay.id)),
        ('total_fee', str(int(pay_amount * 100))),
        ('spbill_create_ip', _get_device_ip(info)),
        ('notify_url', '{}/pay/api/{}/xinfutongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    j = json.dumps(parameter_dict)
    _LOGGER.info("xinfutongpay create: %s", j)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=j, headers=headers, timeout=5, verify=False)
    _LOGGER.info("xinfutongpay create rsp : %s", response.text)
    return {'charge_info': json.loads(response.text)['pay_url']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("xinfutongpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('xinfutongpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['result_code'])
    trade_no = data['platform_trade_no']
    total_fee = float(data['total_fee']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # SUCCESS / FAIL
    if trade_status == 'SUCCESS':
        _LOGGER.info('xinfutongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('nonce', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())),
        ('out_trade_no', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    j = json.dumps(parameter_dict)
    _LOGGER.info('xinfutongpay query data, %s', j)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=j, headers=headers, timeout=3, verify=False)
    _LOGGER.info('xinfutongpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['result_code'])
        total_fee = float(data['total_fee']) / 100.0
        trade_no = data['platform_trade_no']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 入款状态（W - 待入款，S - 入款成功）
        if trade_status == 'SUCCESS':
            _LOGGER.info('xinfutongpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
